import {
  CustomerChannelVO,
  getCustomerChannelPage,
  removeCustomerChannel,
  saveCustomerChannel,
  updateCustomerChannel,
} from '@/services/CustomerChannelService'
import { CustomerUpdateDTO } from '@/services/CustomerService'
import { EditableProTable, ProColumns, ProFormColorPicker } from '@ant-design/pro-components'
import { RecordKey } from '@ant-design/pro-utils/es/useEditableArray'
import { Button, message, Tag } from 'antd'
import React, { useState } from 'react'

const ChannelSetting = () => {
  let [editableKeys, setEditableKeys] = useState<React.Key[]>()

  const columns: ProColumns<CustomerChannelVO>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      hideInTable: true,
    },
    {
      title: '渠道名',
      dataIndex: 'channelName',
      editable: () => true,
    },
    {
      title: '标签颜色',
      dataIndex: 'color',
      renderFormItem: () => <ProFormColorPicker />,
      render: (_, record) => <Tag color={record.color}>{record.color}</Tag>,
      editable: () => true,
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <Button key={record.id} type="link" onClick={() => action?.startEditable?.(record.id)}>
          编辑
        </Button>,
      ],
    },
  ]
  return (
    <>
      <EditableProTable<CustomerChannelVO>
        rowKey="id"
        columns={columns}
        request={async () => getCustomerChannelPage({ current: 1, size: 500 })}
        recordCreatorProps={{
          // 每次新增的时候需要Key
          record: () => ({ id: `-${Math.random().toFixed(0)}` } as CustomerChannelVO),
          creatorButtonText: '新增渠道',
        }}
        editable={{
          editableKeys,
          type: 'multiple',
          onChange: (editableKeys) => setEditableKeys(editableKeys),
          onSave: async (key: RecordKey, value: CustomerUpdateDTO) => {
            console.log(value)
            if (value.id?.startsWith('-')) {
              value.id = undefined
              saveCustomerChannel(value).then(message.success('添加成功'))
              return true
            }
            updateCustomerChannel(value).then(message.success('更新成功'))
            return true
          },
          onDelete: async (key: RecordKey, value: CustomerUpdateDTO) => {
            removeCustomerChannel(value?.id || '0').then(message.success('删除成功'))
            return true
          },
        }}
      />
    </>
  )
}

export default ChannelSetting
